<template>
  <div class="contract-address">
    <a-card title="地址管理">
      <div slot="extra">
        <a-button type="primary" @click="addModal">添加地址</a-button>
      </div>
      <s-table
        bordered
        ref="table"
        size="middle"
        :row-key="(record) => record.id"
        :columns="addressColumns"
        :data="addressData"
      >
        <template slot="action" slot-scope="text, record">
          <a-button size="small" type="primary" @click="editModal(record.id)" style="margin-right: 10px;">编辑</a-button>
          <a-popconfirm
            title="确定删除吗"
            ok-text="确定"
            cancel-text="取消"
            @confirm="onDel(record.id)"
          >
            <a-button size="small" type="danger">删除</a-button>
          </a-popconfirm>
        </template>
      </s-table>
    </a-card>
    <a-modal
      centered
      title="添加客户地址"
      v-model="addVisible"
      @ok="onSubmit"
      @cancel="resetForm"
    >
      <a-form-model
        ref="form"
        :rules="ruleForm"
        :model="form"
      >
        <a-form-model-item :style="{ marginBottom: '5px' }" label="姓名" prop="name">
          <a-input v-model="form.name" type="text" />
        </a-form-model-item>
        <a-form-model-item :style="{ marginBottom: '5px' }" label="联系电话" prop="phone">
          <a-input v-model="form.phone" type="text" />
        </a-form-model-item>
        <a-form-model-item :style="{ marginBottom: '5px' }" label="所在地区" prop="area">
          <Cascader
            :field-names="fieldNames"
            :options="options"
            :load-data="loadData"
            @change="onChange"
            style="width: 100%"
            change-on-select
            placeholder="选择省市区"
          />
        </a-form-model-item>
        <a-form-model-item :style="{ marginBottom: '5px' }"label="详细地址" prop="address_xx">
          <a-textarea v-model="form.address_xx"></a-textarea>
        </a-form-model-item>
        <a-form-model-item :style="{ marginBottom: '5px' }" label="物流名称" prop="logistics_name">
          <a-input v-model="form.logistics_name" type="text" />
        </a-form-model-item>
        <a-form-model-item :style="{ marginBottom: '5px' }" label="物流单号" prop="logistics_no">
          <a-input v-model="form.logistics_no" type="text" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      centered
      title="编辑客户地址"
      v-model="editVisible"
      @ok="onEdit"
      @cancel="resetForm"
    >
      <a-form-model
        ref="form"
        :rules="ruleForm"
        :model="form"
      >
        <a-form-model-item :style="{ marginBottom: '5px' }" label="姓名" prop="name">
          <a-input v-model="form.name" type="text" />
        </a-form-model-item>
        <a-form-model-item :style="{ marginBottom: '5px' }" label="联系电话" prop="phone">
          <a-input v-model="form.phone" type="text" />
        </a-form-model-item>
        <a-form-model-item :style="{ marginBottom: '5px' }" label="所在地区" prop="area">
          <Cascader
            :default-value="defaultAddress"
            :field-names="fieldNames"
            :options="options"
            :load-data="loadData"
            @change="onChange"
            style="width: 100%"
            change-on-select
            placeholder="选择省市区"
          />
        </a-form-model-item>
        <a-form-model-item :style="{ marginBottom: '5px' }"label="详细地址" prop="address_xx">
          <a-textarea v-model="form.address_xx"></a-textarea>
        </a-form-model-item>
        <a-form-model-item :style="{ marginBottom: '5px' }" label="物流名称" prop="logistics_name">
          <a-input v-model="form.logistics_name" type="text" />
        </a-form-model-item>
        <a-form-model-item :style="{ marginBottom: '5px' }" label="物流单号" prop="logistics_no">
          <a-input v-model="form.logistics_no" type="text" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
  import { Cascader } from 'ant-design-vue'
  import { STable } from '@/components'
  import contractColumns from '@/columns/contract'
  import { delAddress, getAddressList, getAddress, addAddress, getEditAddr, editAddr } from '@/api/contract'
  import { getCity } from '@/api/common'
  const addressColumns = contractColumns.address
  export default {
    components: {
      STable,
      Cascader
    },
    props: {
      query: {
        type: Object,
        default: () => {}
      }
    },
    name: 'Address',
    data () {
      return {
        addressColumns,
        addressData: parameters => {
          return getAddressList(Object.assign(parameters, this.queryParam)).then(res => {
            return res.result
          })
        },
        addVisible: false,
        editVisible: false,
        queryParam: {},
        form: {
          name: '',
          phone: '',
          province: '',
          city: '',
          area: '',
          address_xx: '',
          logistics_name: '',
          logistics_no: ''
        },
        ruleForm: {
          name: [
            { required: true, message: '必须填写姓名', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '必须填写联系电话', trigger: 'blur' }
          ],
          area: [
            { required: true, message: '选择所在区域', trigger: 'change' }
          ],
          address_xx: [
            { required: true, message: '必须填写详细地址', trigger: 'blur' }
          ]
        },
        options: [],
        fieldNames: {
          label: 'fullname',
          value: 'id',
          children: 'children'
        },
        addressParams: {
          parent_id: '0'
        },
        defaultAddress: [],
        level: 0,
        addressId: 0
      }
    },
    created () {
      this.init()
    },
    methods: {
      init () {
        const params = {}
        params['filter[contract_id]'] = this.query['contract_id']
        this.queryParam = params
        this.initData()
      },
      addModal () {
        const app = this
        getAddress(app.queryParam['filter[contract_id]']).then(res => {
          if (res.status === 0) {
            app.form.name = res.result.contract_address.name
            app.form.phone = res.result.contract_address.phone
            app.addVisible = true
          } else {
            app.$warning({
              title: res.msg
            })
          }
        })
      },
      editModal (id) {
        const app = this
        const params = Object.assign({ contract_id: app.query['contract_id'] }, { id: id })
        const arr = []
        app.addressId = id
        getEditAddr(params).then(res => {
          if (res.status === 0) {
            app.form = res.result.contract_address
            for (const k in app.options) {
              if (app.options[k].fullname === app.form['province']) {
                arr.push(app.options[k].id)
                getCity(arr[0]).then(res => {
                  const city = res.result.list
                  app.options[k].children = city
                  for (const j in city) {
                    if (city[j].fullname === app.form['city']) {
                      arr.push(city[j].id)
                      getCity(arr[1]).then(res => {
                        const area = res.result.list
                        app.options[k].children[j].children = area
                        for (const f in area) {
                          if (area[f].fullname === app.form['area']) {
                            arr.push(area[f].id)
                          }
                        }
                      })
                    }
                  }
                })
              }
            }
            app.defaultAddress = arr
            app.editVisible = true
          } else {
            app.$warning({
              title: res.msg
            })
          }
        })
      },
      onDel (id) {
        const app = this
        const params = Object.assign({ contract_id: app.query['contract_id'] }, { id: id })
        delAddress(params).then(res => {
          if (res.status === 0) {
            app.$refs.table.refresh(true)
          } else {
            app.$warning({
              title: res.msg
            })
          }
        })
      },
      onSubmit () {
        const app = this
        app.$refs.form.validate(valid => {
          if (valid) {
            const form = {}
            for (const k in app.form) {
              form['contract_address[' + k + ']'] = app.form[k]
            }
            form['contract_id'] = app.query['contract_id']
            addAddress(form).then(res => {
              if (res.status === 0) {
                app.addVisible = false
                app.$refs.table.refresh(true)
              } else {
                app.$info({
                  title: res.msg
                })
              }
            })
          } else {
            return false
          }
        })
      },
      onEdit () {
        const app = this
        app.$refs.form.validate(valid => {
          if (valid) {
            const form = {}
            for (const k in app.form) {
              form['contract_address[' + k + ']'] = app.form[k]
            }
            form['contract_id'] = app.query['contract_id']
            form.id = app.addressId
            editAddr(form).then(res => {
              if (res.status === 0) {
                app.editVisible = false
                app.$refs.table.refresh(true)
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          } else {
            return false
          }
        })
      },
      initData (id = 0) {
        const options = []
        getCity(id).then(res => {
          const list = res.result.list
          for (const k in list) {
            list[k].isLeaf = false
            options.push(list[k])
          }
          this.options = options
        })
      },
      loadData (selectedOptions) {
        const targetOption = selectedOptions[selectedOptions.length - 1]
        targetOption.loading = true
        getCity(targetOption.id)
          .then(res => {
            const list = res.result.list
            targetOption.loading = false
            if (this.level === 2) {
              for (const k in list) {
                list[k].isLeaf = true
              }
            } else {
              for (const k in list) {
                list[k].isLeaf = false
              }
            }
            targetOption.children = list
            this.options = [...this.options]
          })
      },
      onChange (value, selectedOptions) {
        const app = this
        app.level = value.length
        for (const k in selectedOptions) {
          if (k === '0') {
            app.form['province'] = selectedOptions[k].fullname
          }
          if (k === '1') {
            app.form['city'] = selectedOptions[k].fullname
          }
          if (k === '2') {
            app.form['area'] = selectedOptions[k].fullname
          }
        }
      },
      resetForm () {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style scoped>

</style>
